package mylooks.greenteam;

import java.io.ByteArrayOutputStream;
import java.sql.Date;






import mylooks.greenteam.Registration.User;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class DatabaseHelper extends SQLiteOpenHelper 
{
	final static String DBNAME = "mylook";
	final static int version = 1;
	
	Context myContext;
	SQLiteDatabase database;
	Cursor selectCursor;
	
	public DatabaseHelper(Context context)
	{
		super(context, DBNAME, null, version);
		
		myContext = context;
		
		GetWritableDatabase();
		CloseConnection();
	}

	@Override
	public void onCreate(SQLiteDatabase db) 
	{
		db.execSQL("CREATE TABLE 'users' ('idusers' INTEGER PRIMARY KEY NOT NULL,   " +
		"'name' varchar(45) NOT NULL,   " +
		"'surname' varchar(45) NOT NULL,   " +
		"'avatar' varchar(45) NOT NULL,   " +
		"'birthdate' date NOT NULL,   " +
		"'gender' varchar(1) NOT NULL);");		
	}
	
	public boolean isUserAlreadyRegisterd()
	{
		boolean result = false;
		
		GetReadableDatabase();
		
		selectCursor = database.rawQuery("SELECT * FROM users", null);
		
		if(selectCursor.moveToFirst())
			result = true;
		
		CloseConnection();
		
		return result;
	}
	
	public boolean InsertUser(User u)
	{
		boolean result = false;
		
		GetWritableDatabase();
		
		try
		{
			Bitmap photo = u.getAvatar();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.PNG, 85, bos);
			byte[] bArray = bos.toByteArray(); 
			database.execSQL("INSERT INTO users (name, surname,avatar,birthdate, gender) VALUES " +
					"('" + u.getName() + "', '" + u.getSurname() + "', '"+ bArray+"', '"+ u.getBirthdate() + "', '" + String.valueOf(u.getGender()) +"');");
			
			result = true;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		CloseConnection();
		
		return result;
	}
	
	public User GetUser()
	{
		GetReadableDatabase();
				
		selectCursor = database.rawQuery("SELECT * FROM users", null);
		if(selectCursor.moveToFirst())
		{		
			byte[] blob= selectCursor.getBlob(3);
			Bitmap bmp=BitmapFactory.decodeByteArray(blob,0,blob.length);
			return new User(selectCursor.getString(1), selectCursor.getString(2),Date.valueOf(selectCursor.getString(4)), selectCursor.getString(5).charAt(0),bmp);
		}
		
		CloseConnection();
		
		return null;
	}
	
	private void GetWritableDatabase()
	{
		database = getWritableDatabase();
	}
	
	private void GetReadableDatabase()
	{
		database = getReadableDatabase();
	}
	
	private void CloseConnection()
	{
		if(database != null)
			database.close();
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {}

}
